package com.wanmait.translate.configuration.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)  {
        //创建自定义redis模板，
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object> ();
        template.setConnectionFactory(redisConnectionFactory);
        //设置序列化方式
        Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
        //新建jackson中的objectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        //设置jackson为指定序列化方式
        ser.setObjectMapper(objectMapper);
        //定义string类型的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //设置key为string类型的序列化
        template.setKeySerializer(stringRedisSerializer);
        //设置hash的key为string类型的序列化
        template.setHashKeySerializer(stringRedisSerializer);
        //value的序列化为自定义的jackson序列化方式
        template.setValueSerializer(ser);
        template.setHashKeySerializer(ser);
        //结束配置
        template.afterPropertiesSet();
        return template;
    }
}
